<?php

namespace app\system\controller;

use app\api\service\ReportService;
use app\system\BaseController;
use app\system\service\StockService;
use think\db\exception\DbException;
use think\helper\Arr;

class Report extends BaseController
{

    private StockService $stockService;
    private ReportService $reportService;

    public function initialize()
    {
        $this->stockService = new StockService();
        $this->reportService = new ReportService();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 首页面板数据
     * @return \think\response\Json
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function dashboard(): \think\response\Json
    {
        if(!$stockId = $this->request->get('stock_id')) {
            return $this->error('缺少必要参数stock_id');
        }

        $data = [
            'stock_info' => $this->stockService->read($stockId),
            'report_info' => $this->reportService->dashboard($stockId)
        ];
        return $this->success($data);
    }

    /**
     * 粮情数据详情
     * @return \think\response\Json
     */
    public function grainSituation(): \think\response\Json
    {
        [$isOk, $result] = $this->reportService->grainSituation($this->request->all());
        return $isOk ? $this->success($result) : $this->error($result);
    }

    /**
     * 粮情数据详情历史
     * @throws DbException
     */
    public function grainSituationHistory(): \think\response\Json
    {
        if(!$params = $this->request->all()) {
            return $this->error('缺少必要参数');
        }
        if(!Arr::get($params, 'stock_id')) {
            return $this->error('缺少必要参数stock_id');
        }

        return $this->success($this->reportService->grainSituationHistory($params));
    }

    public function statistics()
    {
        return $this->success($this->reportService->statistics());
    }
}